package com.yzy.config.cors;

import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

import java.util.ArrayList;
import java.util.List;

@Configuration
public class CorsConfig {

    @Bean
    public FilterRegistrationBean corsFilter() {
        CorsConfiguration config = new CorsConfiguration();
        config.addAllowedOrigin("*"); // 请求ip和端口
        config.setAllowCredentials(true); //允许携带cookie
        config.setMaxAge(3600L);
        config.setAllowedHeaders(CorsConfig.allowedRequestHeaders());  //请求头
        config.setExposedHeaders(CorsConfig.exposedResponseHeaders());
        CorsConfig.addAllowedMethods(config); // 请求方法
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean filter = new FilterRegistrationBean<>(new CorsFilter(source));
        filter.setOrder(0);
        return filter;
    }

    private static List<String> allowedRequestHeaders() {
        List<String> allowHeads = new ArrayList<>();
        allowHeads.add("Origin");
        allowHeads.add("X-Requested-With");
        allowHeads.add("Content-Type");
        allowHeads.add("Accept");
        allowHeads.add("Authorization");
        return allowHeads;
    }

    private static void addAllowedMethods(CorsConfiguration config) {
        config.addAllowedMethod(HttpMethod.POST);
        config.addAllowedMethod(HttpMethod.GET);
        config.addAllowedMethod(HttpMethod.PUT);
        config.addAllowedMethod(HttpMethod.OPTIONS);
        config.addAllowedMethod(HttpMethod.DELETE);
        config.addAllowedMethod(HttpMethod.PATCH);
    }

    private static List<String> exposedResponseHeaders() {
        List<String> allowHeads = new ArrayList<>();
        allowHeads.add("Location");
        return allowHeads;
    }
}